package org.stone926.airschool.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.stone926.airschool.bean.Student;
import org.stone926.airschool.bean.info.AbstractInfo;
import org.stone926.airschool.constant.ErrorCode;
import org.stone926.airschool.dao.StudentDao;

@Service
public class StudentService {
	@Autowired
	private StudentDao studentDao;

	public Student getStudentById(Integer sid) {
		return studentDao.getStudentById(sid);
	}

	public Student getStudentByName(String sname) {
		return studentDao.getStudentByName(sname);
	}

	public int studentLogin(String sname, String password) {
		Student s = getStudentByName(sname);
		if (s == null)
			return -1;

		if (s.getStudentPassword().equals(password))
			return s.getSid();
		else
			return -1;

	}

	public Student getStudentByPhoneNumber(String phonenumber) {
		return studentDao.getStudentByPhoneNumber(phonenumber);
	}

	public AbstractInfo studentRegister(Student student) {
		System.out.println(student);
		if (student == null)
			return new AbstractInfo() {

				@Override
				public boolean isSuccess() {
					return false;
				}

				@Override
				public String getMessage() {
					return "用户名不能为空";
				}

				@Override
				public int getErrorCode() {
					return ErrorCode.STUDENT_NAME_IS_NULL;
				}
				
			};

		if (studentDao.getStudentByName(student.getsName()) != null)
			return new AbstractInfo() {

				@Override
				public boolean isSuccess() {
					return false;
				}

				@Override
				public String getMessage() {
					return "用户名已经被使用";
				}

				@Override
				public int getErrorCode() {
					return ErrorCode.DUPLICATED_STUDENT_NAME;
				}

			};

		if (studentDao.getStudentByPhoneNumber(student.getStudentPhonenumber()) != null)
			return new AbstractInfo() {
				@Override
				public boolean isSuccess() {
					return false;
				}

				@Override
				public String getMessage() {
					return "手机号已被使用，请检查输入是否正确，或个人信息是否泄露";
				}

				@Override
				public int getErrorCode() {
					return ErrorCode.DUPLICATED_STUDENT_PHONENUMBER;
				}
			};

		studentDao.insertStudent(student);

		return new AbstractInfo() {

			@Override
			public boolean isSuccess() {
				return true;
			}

			@Override
			public String getMessage() {
				return "注册成功";
			}

			@Override
			public int getErrorCode() {
				return ErrorCode.REGISTER_SUCCESS;
			}

		};
	}
}
